import logging
from logging.handlers import RotatingFileHandler

from flask import Flask

from config import Config


def create_app(config_class=Config):
    """
    Flask 应用工厂函数
    负责初始化应用实例并注册所有扩展和蓝图
    """
    app = Flask(__name__)
    app.config.from_object(config_class)

    # 配置日志系统
    handler = RotatingFileHandler('logs/app.log', maxBytes=10000000, backupCount=5, encoding='utf-8')
    handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    handler.setLevel(logging.INFO)
    app.logger.setLevel(logging.INFO)
    app.logger.addHandler(handler)

    # 第三方库导入与项目导入用空行分隔
    from app.routes.api import api_bp
    from app.modules1.Auto import auto_main
    from app.modules4.web_app import app as order_stats_app
    
    # 工具方法建议按功能分组导入

    app.register_blueprint(api_bp, url_prefix='/api')

    # 注册订单统计模块蓝图
    app.register_blueprint(order_stats_app)
    
    # Create a Click command
    @app.cli.command('auto')
    def auto_command():
        """Run the auto_main command"""
        auto_main()
        
    return app